package com.ktg.mes.dv.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.core.redis.RedisCache;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.dv.domain.*;
import com.ktg.mes.dv.service.IDvMachineryService;
import com.ktg.mes.dv.service.IDvTemperatureDataService;
import com.ktg.mes.dv.service.IDvWarmHumidDataService;
import com.ktg.mes.dv.service.IDvWattHourMeterDataService;
import com.ktg.mes.pro.domain.ProTaskDeviceProcess;
import com.ktg.mes.pro.domain.ProWaring;
import com.ktg.mes.pro.service.IProWaringService;
import com.ktg.mes.rec.domain.RecLnspectionRecord;
import com.ktg.mes.send.XZPost;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;

/**
 * 设备原始数据Controller
 *
 * @author byteco
 * @date 2022-11-29
 */
@Slf4j
@RestController
@RequestMapping("/dv/dvMachineryData")
public class DvMachineryDataController extends BaseController
{
    @Autowired
    private IDvTemperatureDataService temperatureDataService;

    @Autowired
    private IDvWattHourMeterDataService wattHourMeterDataService;

    @Autowired
    private IDvWarmHumidDataService warmHumidDataService;

    @Autowired
    private IProWaringService proWaringService;

    @Autowired
    private IDvMachineryService dvMachineryService;

    private static Map<String,DvMachineryData> mechineryLastIndex = new HashMap<>();

    @Autowired
    private RedisCache redisCache;


    /**
     * 新增设备原始数据,用于设备上传数据
     */
    @Log(title = "新增设备原始数据,用于设备上传数据", businessType = BusinessType.INSERT)
    @PostMapping("/addJson")
    public Result<String> addJson(@RequestBody JSONObject jsonObject, HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增设备原始数据,用于设备上传数据",req,jsonObject);
        try {
            Set<String> keySet = jsonObject.keySet();
            String dID = jsonObject.getString("ID");
            for (String key:keySet) {
                if (key.equals("ID")){
                    continue;
                }

                String deviceCode = dID+":"+key;
                JSONObject machineryJson = jsonObject.getJSONObject(key);

                int deviceType = 0;
                //获取设备当前的任务
                DvMachinery dvMachinery = new DvMachinery();
                //电表
                if (machineryJson.get("RunTime_M_S") != null){
                    dvMachinery.setWattHourMeter(deviceCode);
                    deviceType = 1;
                }
                //温度
                if (machineryJson.get("TEMP1") != null){
                    dvMachinery.setThermometer(deviceCode);
                    deviceType = 2;
                }
                //温湿
                if (machineryJson.get("TEMP_SD") != null){
                    dvMachinery.setWarmHumid(deviceCode);
                    deviceType = 3;
                }

                QueryWrapper<DvMachinery> dvMachineryQueryWrapper = new QueryWrapper<>(dvMachinery);
                dvMachineryQueryWrapper.last(" limit 1");
                dvMachinery = dvMachineryService.getOne(dvMachineryQueryWrapper);

                if (dvMachinery == null){
                    dvMachinery = new DvMachinery();
                    dvMachinery.setMachineryId(0L);
                    dvMachinery.setEquipmentCode(deviceCode);
                    dvMachinery.setMachineryName("");
                }

                //获取设备当前的任务和工序
                ProTaskDeviceProcess taskDeviceProcess = ProTaskDeviceProcess.getMachineryNowTaskProcess(redisCache,dvMachinery.getMachineryId());

                boolean isTaskDeviceProcessNull = false;
                if (taskDeviceProcess == null){
                    taskDeviceProcess = new ProTaskDeviceProcess();
                    taskDeviceProcess.setRecordId(0L);
                    taskDeviceProcess.setTaskId("0");
                    taskDeviceProcess.setProcessId(0L);
                    isTaskDeviceProcessNull = true;
                }

                //保存设备数据记录，判断设备类型
                DvWattHourMeterData meterData = null;
                DvTemperatureData temperatureData = null;
                DvWarmHumidData warmHumidData = null;
                if (deviceType == 1) {
                    meterData = new DvWattHourMeterData();
                    meterData.setCreateTime(new Date());
                    meterData.setTaskDeviceProcessRecordId(taskDeviceProcess.getRecordId());
                    meterData.setTaskId(taskDeviceProcess.getTaskId());
                    meterData.setTaskName(taskDeviceProcess.getTaskName());
                    meterData.setBatchNo(taskDeviceProcess.getBatchNo());
                    meterData.setProcessId(taskDeviceProcess.getProcessId());
                    meterData.setProcessName(taskDeviceProcess.getProcessName());
                    meterData.setDeviceId(dvMachinery.getMachineryId());
                    meterData.setDeviceCode(dvMachinery.getEquipmentCode());
                    meterData.setDeviceName(dvMachinery.getMachineryName());
                    meterData.fromJSON(machineryJson);
                    wattHourMeterDataService.insert(meterData);
                }else if (deviceType == 2) {
                    temperatureData = new DvTemperatureData();
                    temperatureData.setCreateTime(new Date());
                    temperatureData.setTaskDeviceProcessRecordId(taskDeviceProcess.getRecordId());
                    temperatureData.setTaskId(taskDeviceProcess.getTaskId());
                    temperatureData.setTaskName(taskDeviceProcess.getTaskName());
                    temperatureData.setBatchNo(taskDeviceProcess.getBatchNo());
                    temperatureData.setProcessId(taskDeviceProcess.getProcessId());
                    temperatureData.setProcessName(taskDeviceProcess.getProcessName());
                    temperatureData.setDeviceId(dvMachinery.getMachineryId());
                    temperatureData.setDeviceCode(dvMachinery.getEquipmentCode());
                    temperatureData.setDeviceName(dvMachinery.getMachineryName());
                    temperatureData.fromJSON(machineryJson);
                    temperatureDataService.save(temperatureData);
                }else {
                    warmHumidData = new DvWarmHumidData();
                    warmHumidData.setCreateTime(new Date());
                    warmHumidData.setTaskDeviceProcessRecordId(taskDeviceProcess.getRecordId());
                    warmHumidData.setTaskId(taskDeviceProcess.getTaskId());
                    warmHumidData.setTaskName(taskDeviceProcess.getTaskName());
                    warmHumidData.setBatchNo(taskDeviceProcess.getBatchNo());
                    warmHumidData.setProcessId(taskDeviceProcess.getProcessId());
                    warmHumidData.setProcessName(taskDeviceProcess.getProcessName());
                    warmHumidData.setDeviceId(dvMachinery.getMachineryId());
                    warmHumidData.setDeviceCode(dvMachinery.getEquipmentCode());
                    warmHumidData.setDeviceName(dvMachinery.getMachineryName());
                    warmHumidData.fromJSON(machineryJson);
                    warmHumidDataService.insert(warmHumidData);
                }

                RecLnspectionRecord recLnspectionRecord  = RecLnspectionRecord.getMachineryNowProductProcess(redisCache,taskDeviceProcess.getDeviceId());


                //设备最大温度警告处理
                if(deviceType == 2){
                    if (dvMachinery != null && dvMachinery.getWarningTemp() != null && dvMachinery.getWarningDuration() != null){
                        float maxTemp = dvMachinery.getWarningTemp();
                        float maxTime = dvMachinery.getWarningDuration();
                        if (temperatureData != null && temperatureData.getRecordId() > 0){
                            String maxKey = "设置最大温度："+dvMachinery.getMachineryId();
                            if (temperatureData.getTemp1() > maxTemp){
                                //获取旧数据
                                DvTemperatureData oldItem = redisCache.getCacheObject(maxKey);
                                if (oldItem != null){
                                    oldItem.getCreateTime().setTime((long) (oldItem.getCreateTime().getTime()+maxTime));
                                    if (oldItem.getCreateTime().before(temperatureData.getCreateTime())){
                                        ProWaring proWaring = new ProWaring();
                                        proWaring.setType(ProWaring.type温度);
                                        proWaring.setCreateTime(new Date());
                                        proWaring.setTaskName(taskDeviceProcess.getTaskName());
                                        proWaring.setBatchNo(taskDeviceProcess.getBatchNo());
                                        proWaring.setDeviceCode(temperatureData.getDeviceCode());
                                        proWaring.setDeviceName(temperatureData.getDeviceName());
                                        proWaring.setProcessName(taskDeviceProcess.getProcessName());
                                        if (recLnspectionRecord != null){
                                            proWaring.setBucket(recLnspectionRecord.getToolTypeName());
                                            proWaring.setRecordId(recLnspectionRecord.getId().toString());
                                        }
                                        proWaring.setMachineryDataId(temperatureData.getRecordId());
                                        proWaring.setRemark(machineryJson.toJSONString());

                                        proWaring.setDes("当前：机器运行运行温度超过设备设定值！");
                                        proWaringService.save(proWaring);

                                        if (StringUtils.isNotEmpty(dvMachinery.getWarningDeviceCode())
                                                && StringUtils.isNotEmpty(dvMachinery.getWarningDeviceCode())){
                                            MultiValueMap map = new LinkedMultiValueMap();
                                            map.add("id", dvMachinery.getWarningDeviceCode());
                                            map.add("data",dvMachinery.getWarningDeviceValue());
                                            XZPost.sendPOSTRequest("http://192.168.1.225:8283/api/v1/sendH",map);
                                        }
                                    }
                                }else {
                                    redisCache.setCacheObject(maxKey,temperatureData);
                                }
                            }else {
                                redisCache.deleteObject(maxKey);
                            }
                        }
                    }
                }



//                // 工艺设置参数设备数据，警告处理
//                if (!isTaskDeviceProcessNull &&  recLnspectionRecord != null){
//                    //判断设备类型
//                    if (deviceType == 1){
//                        //获取机器上一个状态
//                        if (meterData.getZszgl() >= 1){
//                            //启动中
//                            if (recLnspectionRecord.getStartTime() == null){
//                                recLnspectionRecord.setStartTime(new Date());
//                            }
//                            Integer secondValue = recLnspectionRecord.getShiChang();
//                            if (secondValue == null){
//                                secondValue = 0;
//                            }
//                            Double lastZszgl = recLnspectionRecord.getLastStatus();
//
//                            //判断上一次也是启动中
//                            if (lastZszgl != null && lastZszgl >= 1){
//                                Integer lastRuntime = recLnspectionRecord.getLastIndex();
//                                //判断没有重启
//                                if (lastRuntime == null){}
//                                if (lastRuntime < meterData.getRuntime()){
//                                    Integer subCount = meterData.getRuntime() - lastRuntime;
//                                    if (subCount < 60*5){
//                                        secondValue = secondValue + subCount;
//                                    }
//                                }
//
//                                //判断研磨，分散时间是否超时
//                                Integer max = getShiChangRuleFromProRouteProcess(taskDeviceProcess.getParamJson(),1);
//                                if (max != null && secondValue > max){
//                                    ProWaring proWaring = new ProWaring();
//                                    proWaring.setType(ProWaring.type采集记录);
//                                    proWaring.setCreateTime(new Date());
//                                    proWaring.setTaskName(taskDeviceProcess.getTaskName());
//                                    proWaring.setBatchNo(taskDeviceProcess.getBatchNo());
//                                    proWaring.setDeviceCode(recLnspectionRecord.getMachineryCode());
//                                    proWaring.setDeviceName(recLnspectionRecord.getMachineryName());
//                                    proWaring.setProcessName(taskDeviceProcess.getProcessName());
//                                    proWaring.setBucket(recLnspectionRecord.getToolTypeName());
//                                    proWaring.setRecordId(recLnspectionRecord.getId().toString());
//                                    proWaring.setMachineryDataId(meterData.getRecordId());
//                                    proWaring.setRemark(machineryJson.toJSONString());
//
//                                    proWaring.setDes("当前：机台还在运行，运行时长已经大于工艺配置的最大值");
//                                    proWaringService.save(proWaring);
//                                }
//                            }
//                            recLnspectionRecord.setLastIndex(meterData.getRuntime());
//                            recLnspectionRecord.setShiChang(secondValue);
//                            recLnspectionRecord.setLastStatus(meterData.getZszgl());
//                            recLnspectionRecord.setMachineryNowProductProcessToRedisCache(redisCache);
//
//
//                        }else {
//                            Double lastZszgl = recLnspectionRecord.getLastStatus();
//                            //如果上一次是运行中
//                            if (lastZszgl != null && lastZszgl >= 1){
//                                Integer secondValue = recLnspectionRecord.getShiChang();
//                                if (secondValue == null){
//                                    secondValue = 0;
//                                }
//                                Integer lastRuntime = recLnspectionRecord.getLastIndex();
//                                //判断没有重启
//                                if (lastRuntime < meterData.getRuntime()){
//                                    secondValue = secondValue + meterData.getRuntime() - lastRuntime;
//                                    recLnspectionRecord.setShiChang(secondValue);
//
//                                    //判断研磨，分散时间是否超时
//                                    Integer min = getShiChangRuleFromProRouteProcess(taskDeviceProcess.getParamJson(),0);
//                                    if (min != null && secondValue < min){
//                                        ProWaring proWaring = new ProWaring();
//                                        proWaring.setType(ProWaring.type采集记录);
//                                        proWaring.setCreateTime(new Date());
//                                        proWaring.setTaskName(taskDeviceProcess.getTaskName());
//                                        proWaring.setBatchNo(taskDeviceProcess.getBatchNo());
//                                        proWaring.setDeviceCode(recLnspectionRecord.getMachineryCode());
//                                        proWaring.setDeviceName(recLnspectionRecord.getMachineryName());
//                                        proWaring.setProcessName(taskDeviceProcess.getProcessName());
//                                        proWaring.setBucket(recLnspectionRecord.getToolTypeName());
//                                        proWaring.setRecordId(recLnspectionRecord.getId().toString());
//                                        proWaring.setMachineryDataId(meterData.getRecordId());
//                                        proWaring.setRemark(machineryJson.toJSONString());
//
//                                        proWaring.setDes("当前：机台已停止，运行时长小于工艺配置的最小值");
//                                        proWaringService.save(proWaring);
//                                    }
//                                }
//
//                                recLnspectionRecord.setLastIndex(meterData.getRuntime());
//                                recLnspectionRecord.setLastStatus(meterData.getZszgl());
//                                //保存到
//                                recLnspectionRecord.setMachineryNowProductProcessToRedisCache(redisCache);
//                            }
//                        }
//                    }
//                    else if (deviceType == 2){
//                        //跟新最大温度值
//                        Double wendu = recLnspectionRecord.getWenDu();
//
//                        Double ruleWenDu = getWenDuRuleFromProRouteProcess(taskDeviceProcess.getParamJson());
//                        if (ruleWenDu != null && temperatureData.getTemp1() > ruleWenDu){
//                            ProWaring proWaring = new ProWaring();
//                            proWaring.setType(ProWaring.type采集记录);
//                            proWaring.setCreateTime(new Date());
//                            proWaring.setTaskName(taskDeviceProcess.getTaskName());
//                            proWaring.setBatchNo(taskDeviceProcess.getBatchNo());
//                            proWaring.setDeviceCode(recLnspectionRecord.getMachineryCode());
//                            proWaring.setDeviceName(recLnspectionRecord.getMachineryName());
//                            proWaring.setProcessName(taskDeviceProcess.getProcessName());
//                            proWaring.setBucket(recLnspectionRecord.getToolTypeName());
//                            proWaring.setRecordId(recLnspectionRecord.getId().toString());
//                            proWaring.setMachineryDataId(temperatureData.getRecordId());
//                            proWaring.setRemark(machineryJson.toJSONString());
//
//                            proWaring.setDes("当前：机台已停止，运行时长小于工艺配置的最小值");
//                            proWaringService.save(proWaring);
//                        }
//
//                        if (wendu == null || temperatureData.getTemp1() > wendu){
//                            recLnspectionRecord.setWenDu(temperatureData.getTemp1());
//                            recLnspectionRecord.setMachineryNowProductProcessToRedisCache(redisCache);
//                        }
//                    }
//                }
            }

            return apiLog.ok("添加成功！");
        }catch (Exception e){
            log.error("设备数据上传处理失败",e);
            ProWaring proWaring = new ProWaring();
            proWaring.setCreateTime(new Date());
            proWaring.setRemark(jsonObject.toJSONString());
            proWaring.setMachineryDataId(0L);
            proWaring.setBatchNo("0");
            proWaring.setDes("数据处理报错:"+e.getLocalizedMessage());
            proWaringService.save(proWaring);
            return apiLog.error(e);
        }
    }





    /**
     * 新增设备原始数据,用于设备上传数据
     */
    @GetMapping("/addJson2")
    public Result<String> addJson2(DvMachineryType dvMachineryType, HttpServletRequest req)
    {
        return Result.OK("111111111");
    }






    /**
     * 用于获取配置参数的最大，最小值
     * @param paramJson
     * @param index 0 最小值 1最大值
     * @return
     */
    public Integer getShiChangRuleFromProRouteProcess(String paramJson,int index){
        //判断研磨，分散时间是否超时
        if (paramJson == null || paramJson.length() < 5){
            return null;
        }
        JSONObject param = JSONObject.parseObject(paramJson);
        String aStr = param.getString(DvMachineryData.param研磨时长);
        if (aStr == null){
            aStr = param.getString(DvMachineryData.param分散时长);
        }
        if (!StringUtils.isEmpty(aStr)) {
            //去掉后面的单位
            int unitIndex = aStr.indexOf("(");
            aStr = aStr.substring(0, unitIndex);
            String[] list = aStr.split("-");
            if (list.length > index) {
                return Integer.valueOf(list[index]) * 60;
            }
        }
        return null;
    }


    /**
     * 用于获取配置参数的最大，最小值
     * @param paramJson
     * @param index 0 最小值 1最大值
     * @return
     */
    public Double getWenDuRuleFromProRouteProcess(String paramJson){
        //判断研磨，分散时间是否超时
        //判断研磨，分散时间是否超时
        if (paramJson == null || paramJson.length() < 5){
            return null;
        }
        JSONObject param = JSONObject.parseObject(paramJson);
        String aStr = param.getString(DvMachineryData.param研磨温度);
        if (!StringUtils.isEmpty(aStr)) {
            //去掉后面的单位
            int index = aStr.indexOf("(");
            aStr = aStr.substring(0, index);
            aStr = aStr.replace("≤","");
            return Double.valueOf(aStr);
        }
        return null;
    }

}
